﻿using EShopV20.Models;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace EShopV20.Areas.Adm.ActionFilters
{
    public class SecurityAttribute: ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            if (filterContext.HttpContext.Request.IsAuthenticated == false)
            {
                filterContext.HttpContext.Response.Redirect("/Adm/Admin/Login?Authenticate=1");
                return;
            }

            var sdb = new ApplicationDbContext();
            String UserName = filterContext.HttpContext.User.Identity.Name;
            var RoleIds = sdb.Users
                .Single(u => u.UserName == UserName)
                .Roles.Select(ur => ur.RoleId).ToList();

            //File.AppendAllText("c:/temp/mvc-logs.txt", RoleIds.ToString());

            var ActionName = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName 
                + "/" + filterContext.ActionDescriptor.ActionName;

            File.AppendAllText("c:/temp/mvc-logs.txt", ActionName);

            var db = new EShopV20DbContext();
            var perms = db.Permissions
                .Where(p => p.WebAction.Name == ActionName 
                    && RoleIds.Contains(p.RoleId)).ToList();

            if (perms.Count > 0 && perms.All(p=>p.Allow == false))
            {
                filterContext.HttpContext.Response.Redirect("/Adm/Admin/Login?Authorize=1");
                return;
            }

            //File.AppendAllText("c:/temp/mvc-logs.txt", perms.ToString());
        }
    }
}